<script setup lang="ts">
import {
  useColorMode,
  useEventListener,
  useFullscreen,
  breakpointsTailwind,
  useBreakpoints
} from '@vueuse/core'
import { useRoute, useRouter } from 'vue-router'
import * as Lang from '@/config/lang'
import type { SizeType } from './config'
import { useUserStore } from '@/stores'
import { useStore } from '@/stores'
import { ElNotification } from 'element-plus'

const router = useRouter()
const route = useRoute()
const appStore = useStore()
const userStore = useUserStore()

// 主题颜色配置
const { system, store } = useColorMode()
// system.value // 系统的颜色模式：'dark' | 'light'
// store.value // 项目的颜色模式：'dark' | 'light' | 'auto'
const mode = computed(() => (store.value === 'auto' ? system.value : store.value))
provide('color-mode', mode)
provide('color-mode-system', system)
provide('color-mode-store', store)

// 水印设置
const watermark = reactive({
  color: 'rgba(0, 0, 0, .15)'
})

watchEffect(() => {
  watermark.color = mode.value === 'dark' ? 'rgba(255, 255, 255, .15)' : 'rgba(0, 0, 0, .15)'
})

// 配置多语言
const locale = ref<BusinessLangType>('zhCn')
provide('locale', locale)

// 全局组件大小 'large' | 'default' | 'small'
const size = ref<SizeType>('default')
provide('size', size)

// 对按钮进行配置
const button = {
  autoInsertSpace: true
}

// 对消息进行配置
const message = {
  // 最多弹出 3 个消息提示框
  max: 3
}

// 全局初始化 zIndex 的值
const zIndex = 3000

// 页面刷新
provide('refresh', () => {
  router.replace({ ...route, query: { ...route.query, refresh: Date.now() } })
})

// 页面全屏
const { isFullscreen, toggle } = useFullscreen()
// F11默认全屏效果不能满足这里的需求，禁止默认全屏行为，采用我们项目的全屏逻辑
useEventListener('keydown', (e) => {
  if (e.key === 'F11') {
    // 禁用f11
    e.preventDefault()
    toggle()
  }
})
provide('is-full-screen', isFullscreen)
provide('full-screen', toggle)

// 页面适配断点
const breakpoints = useBreakpoints(breakpointsTailwind)
// 小于等于 1024px 都会 true
const lgAndSmaller = breakpoints.smallerOrEqual('lg')
watchEffect(() => {
  userStore.collapse = lgAndSmaller.value
})
provide('<=lg', lgAndSmaller)

// 全局提示
watchEffect(() => {
  if (appStore.lastMessage) {
    ElNotification({
      title: '系统提示',
      message: appStore.lastMessage
    })
    appStore.lastMessage = ''
  }
})

// 全局指令
watchEffect(() => {
  if (appStore.command === 'TokenExpired') {
    userStore.$reset()
    router.replace('/login')
    appStore.command = ''
  }
})
</script>

<template>
  <el-config-provider
    :size="size"
    :z-index="zIndex"
    :locale="Lang[locale]"
    :button="button"
    :message="message"
  >
    <el-watermark :font="watermark" content="Skyline">
      <RouterView />
    </el-watermark>
  </el-config-provider>
</template>

<style scoped></style>
